package com.xpxrule.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.xpxrule.dataobject.biz.model.ReturnResponse;
import com.xpxrule.dataobject.dao.EnumConstant;
import com.xpxrule.dataobject.req.EnumConstantQueryReq;
import com.xpxrule.dataobject.vo.EnumConstantVo;
import com.xpxrule.dataobject.vo.OptionVo;
import com.xpxrule.mapper.ConstantItemMapper;
import com.xpxrule.mapper.EnumConstantMapper;
import com.xpxrule.service.EnumConstantService;
import com.xpxrule.util.ModelConvertUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class EnumConstantServiceImpl implements EnumConstantService {
    @Autowired
    private EnumConstantMapper enumConstantMapper;
    @Autowired
    private ConstantItemMapper constantItemMapper;

    @Override
    public ReturnResponse insert(EnumConstantVo vo) {
        boolean isExist = verifyDbUnique(vo.getConstantKey());
        if (!isExist) {
            return ReturnResponse.fail("The unique verification failed. The new data already exists in the database.");
        }
        EnumConstant dao = ModelConvertUtil.convertEnumConstantVoToEnumConstant(vo);
        int count = enumConstantMapper.insert(dao);
        return ReturnResponse.success(count);
    }

    @Transactional
    @Override
    public ReturnResponse delete(Long id) {
        boolean isExist = verifyDbExistById(id);
        if (!isExist) {
            return ReturnResponse.fail("The data does not exist in the database.");
        }
        EnumConstant enumConstant = enumConstantMapper.selectById(id);
        enumConstant.setIsDeleted(new Date());
        int count = enumConstantMapper.updateById(enumConstant);
        constantItemMapper.deleteConstantItemByConstantKey(enumConstant.getConstantKey());
        return ReturnResponse.success(count);
    }

    @Override
    public ReturnResponse update(EnumConstantVo vo) {
        boolean isExist = verifyDbExistById(Long.valueOf(vo.getId()));
        if (!isExist) {
            return ReturnResponse.fail("The data does not exist in the database.");
        }
        EnumConstant old = enumConstantMapper.selectById(vo.getId());
        ModelConvertUtil.fillEnumConstantFromEnumConstantVo(old, vo);
        int count = enumConstantMapper.updateById(old);
        return ReturnResponse.success(count);
    }

    @Override
    public ReturnResponse<List<EnumConstantVo>> selectList(EnumConstantQueryReq req) {
        List<EnumConstant> list = selectEnumConstantListByReq(req);
        List<EnumConstantVo> resultList = list.stream()
                .map(ModelConvertUtil::convertEnumConstantToEnumConstantVo)
                .collect(Collectors.toList());
        return new ReturnResponse<>(resultList);
    }

    /**
     * 根据查询条件查询枚举常量列表
     * @param req
     * @return
     */
    private List<EnumConstant> selectEnumConstantListByReq(EnumConstantQueryReq req) {
        QueryWrapper<EnumConstant> wrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(req.getConstantKey())) {
            wrapper.like(EnumConstant.COLUMN.CONSTANT_KEY, req.getConstantKey());
        }
        if (!StringUtils.isEmpty(req.getConstantName())) {
            wrapper.like(EnumConstant.COLUMN.CONSTANT_NAME, req.getConstantName());
        }
        if (!ObjectUtils.isEmpty(req.getIsEnable())) {
            wrapper.eq(EnumConstant.COLUMN.IS_ENABLE, req.getIsEnable());
        }
        wrapper.isNull(EnumConstant.COLUMN.IS_DELETED);
        return enumConstantMapper.selectList(wrapper);
    }

    @Override
    public ReturnResponse<List<OptionVo>> getAllEnumConstantOptions() {
        EnumConstantQueryReq req = new EnumConstantQueryReq();
        req.setIsEnable((short) 0);
        List<EnumConstant> list = selectEnumConstantListByReq(req);
        List<OptionVo> resultList = list.stream()
                .map(ModelConvertUtil::convertEnumConstantToOptionVo)
                .collect(Collectors.toList());
        return new ReturnResponse<>(resultList);
    }

    @Override
    public EnumConstant getEnumConstantByConstantKey(String constantKey) {
        QueryWrapper<EnumConstant> wrapper = new QueryWrapper<>();
        wrapper.eq(EnumConstant.COLUMN.CONSTANT_KEY, constantKey);
        wrapper.isNull(EnumConstant.COLUMN.IS_DELETED);
        List<EnumConstant> list = enumConstantMapper.selectList(wrapper);
        if (!CollectionUtils.isEmpty(list) && list.size() != 1) {
            throw new RuntimeException("The data does not exist in the database.");
        }
        return list.get(0);
    }

    /**
     * 校验数据存在
     * @param id
     * @return
     */
    private boolean verifyDbExistById(Long id) {
        QueryWrapper<EnumConstant> wrapper = new QueryWrapper<>();
        wrapper.eq(EnumConstant.COLUMN.ID, id);
        wrapper.isNull(EnumConstant.COLUMN.IS_DELETED);
        Long count = enumConstantMapper.selectCount(wrapper);
        return count == 1;
    }

    /**
     * 校验数据库幂等性
     * @param constantKey
     * @return
     */
    private boolean verifyDbUnique(String constantKey) {
        QueryWrapper<EnumConstant> wrapper = new QueryWrapper<>();
        wrapper.eq(EnumConstant.COLUMN.CONSTANT_KEY, constantKey);
        wrapper.isNull(EnumConstant.COLUMN.IS_DELETED);
        Long count = enumConstantMapper.selectCount(wrapper);
        return count == 0;
    }
}
